package whf.framework.security.acegiimp;

import java.util.Set;

import org.acegisecurity.AuthenticationCredentialsNotFoundException;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.providers.cas.CasAuthoritiesPopulator;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;

import whf.framework.security.UserManager;
import whf.framework.security.entity.Role;
import whf.framework.security.entity.User;

/**
 * 用在Acegi中,用作从数据库中获取用户和用户相关信息,如角色等
 * @author wanghaifeng
 * 
 */
public class UserDetailsServiceImp implements UserDetailsService, CasAuthoritiesPopulator {
	private UserManager userManager;

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	/* (non-Javadoc)
	 * @see org.acegisecurity.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		User user = userManager.findUserByUsername(username);
		Set<Role> roles = userManager.findRoles(user);
		if(user == null){
			throw new UsernameNotFoundException(username);
		}
		try{
			return new UserDetailsImp(user, roles);
		}catch(Exception e){
			throw new DataAccessResourceFailureException("loadUserByUsername", e);
		}
	}
	
	/* (non-Javadoc)
	 * @see org.acegisecurity.providers.cas.CasAuthoritiesPopulator#getUserDetails(java.lang.String)
	 */
	public UserDetails getUserDetails(String username) throws AuthenticationException {
		try{
			return this.loadUserByUsername(username);
		} catch(Exception e){
			throw new AuthenticationCredentialsNotFoundException(username, e);
		}
	}
}
